package com.huawei.classroom.student.h55;

import java.io.Closeable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PoetryAnalysis {
	public PoetryAnalysis() {
		
	}
	/**
	 * 
	 * @param pathFilename 包含诗歌内容的源文件
	 * @param chars 需要统计的字 以半角分号分割 
	 * 统计  
	 * @throws Exception 
	 * 
	 */
	public void analysis(String pathFilename,String chars) {
		try {
			String poem = readFromTxt(pathFilename);
			String[] word = chars.split(";");
			Map<String, Integer> map = new HashMap<String, Integer>();
			for(int j=0; j<poem.length()-1; j++) {
				if(judge(poem.charAt(j)) || judge(poem.charAt(j+1))) {
					continue;
				}
				
				for(int i=0; i<word.length; i++) {
					if(poem.charAt(j) == word[i].charAt(0) || poem.charAt(j+1) == word[i].charAt(0)) {				
						String temp = poem.substring(j, j+2);
						map.put(temp, (map.get(temp) == null ? 1 : map.get(temp) + 1));
						break;
					}
				}
			}
			List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
			Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
				@Override
				public int compare(Map.Entry<String, Integer> a1, Map.Entry<String, Integer> a2) {
					return a2.getValue() - a1.getValue();
				}
			});
			int n = 0;
			for (Map.Entry<String, Integer> entry : list) {
				System.out.println(entry.getKey() + " " + entry.getValue());
				n++;
				if(n == 10) {
					break;
				}
			}
		}catch(Exception e) {
			System.out.println("666");
			e.printStackTrace();
			
		}
		
	}
	
	private String readFromTxt(String filename) throws Exception {
		Reader reader = null;
		try {
			StringBuffer buf = new StringBuffer();
			char[] chars = new char[1024];
			// InputStream in=new FileInputStream(filename);

			reader = new InputStreamReader(new FileInputStream(filename), "UTF-8");
			int readed = reader.read(chars);
			while (readed != -1) {
				buf.append(chars, 0, readed);
				readed = reader.read(chars);
			}
			return buf.toString();
		} finally {
			close(reader);
		}
	}
	
	private void close(Closeable inout) {
		if (inout != null) {
			try {
				inout.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public boolean judge(char a) {
		if(a == ' ' || a == '：' || a == '\t' || a == '，' || 
				a == '\n' || a == '"' || a == '《' || a == '》' || 
				a == '.' || a == '？' || a == '。' || a == '“' || 
				a == '”' || a == '‘' || a == '’' || a == ':' || 
				a == ',' || a == '！' || a == '；' || a == '．' || a == '(' || a == ')' || a == '_')
			return true;
		return false;
	}
}
